﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;

namespace TipTep.SkeletonAnalyzer
{
    public partial class frmMain : Form
    {
        Image handImage = null;
        Image handWithBackImage = null;
        XmlDocument handData = null;
        XmlNode handSkeleton = null;
        /// <summary>
        /// Hand skeleton lines from hand data XML
        /// </summary>
        XmlNodeList handSkeletonLines = null;
        PointF handPoint = Point.Empty;
        Rectangle handRectangle = Rectangle.Empty;        

        public frmMain()
        {
            InitializeComponent();
        }

        #region Form Events      

        private void buttonSelectFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBoxFolderLocation.Text = fd.SelectedPath;
            }
        }

        private void buttonLoad_Click(object sender, EventArgs e)
        {
            LoadHandData();
        }

        private void buttonDrawSkeleton_Click(object sender, EventArgs e)
        {
            DrawSkeleton();
        }

        #endregion

        /// <summary>
        /// Load hand data, images and skeleton
        /// </summary>
        private void LoadHandData()
        {
            if (!string.IsNullOrEmpty(textBoxFolderLocation.Text))
            {
                try
                {
                    string[] files = Directory.GetFiles(textBoxFolderLocation.Text);
                    foreach (string file in files)
                    {
                        if (file.Contains("HandData.xml"))
                        {
                            handData = new XmlDocument();
                            handData.Load(file);
                            handSkeleton = handData.DocumentElement.SelectSingleNode("Skeleton");
                            handSkeletonLines = handSkeleton.SelectNodes("Line");
                            handPoint = new PointF((float)Convert.ToDouble(handData.DocumentElement.SelectSingleNode("HandPoint").Attributes[0].Value),
                            (float)Convert.ToDouble(handData.DocumentElement.SelectSingleNode("HandPoint").Attributes[1].Value));

                            handRectangle = new Rectangle(
                               Convert.ToInt32(handData.DocumentElement.SelectSingleNode("Handrectangle").Attributes["X"].Value),
                               Convert.ToInt32(handData.DocumentElement.SelectSingleNode("Handrectangle").Attributes["Y"].Value),
                               Convert.ToInt32(handData.DocumentElement.SelectSingleNode("Handrectangle").Attributes["Width"].Value),
                               Convert.ToInt32(handData.DocumentElement.SelectSingleNode("Handrectangle").Attributes["Height"].Value)
                                );

                            labelSkeletonLinesCount.Text = handSkeletonLines.Count.ToString();                            
                        }
                        else if (file.Contains("HandImageWithBackground.bmp"))
                        {
                            handWithBackImage = Bitmap.FromFile(file);
                            pictureBoxWithBackground.Image = handWithBackImage;
                        }
                        else if (file.Contains("HandImageWithoutBackground.bmp"))
                        {
                            handImage = Bitmap.FromFile(file);
                            pictureBoxWithoutBackground.Image = handImage;
                        }
                    }
                    DrawSkeleton();

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error on file loading. Details: " + ex.Message);
                }
            }
        }

        /// <summary>
        /// Draw hand skeleton
        /// </summary>
        private void DrawSkeleton()
        {
            if (handData != null)
            {
                Image skeletonImage = null;
                switch (comboBox1.SelectedIndex)
                {
                    case 1: skeletonImage = new Bitmap(handImage); break;//Skeleton on hand image
                    case 2: skeletonImage = new Bitmap(handWithBackImage); break;//Skeleton on hand with background image
                    default: skeletonImage = new Bitmap(handImage.Width, handImage.Height); break;//Only skeleton
                }
                if (handSkeletonLines != null)
                {
                    Graphics gr = Graphics.FromImage(skeletonImage);
                    foreach (XmlNode line in handSkeletonLines)
                    {
                        PointF pStart = new PointF((float)Convert.ToDouble(line.Attributes["StartX"].Value) - handRectangle.X, (float)Convert.ToDouble(line.Attributes["StartY"].Value) - handRectangle.Y);
                        PointF pEnd = new PointF((float)Convert.ToDouble(line.Attributes["EndX"].Value) - handRectangle.X, (float)Convert.ToDouble(line.Attributes["EndY"].Value) - handRectangle.Y);
                        //gr.FillPolygon(Brushes.Red, new PointF[] { new PointF(pStart.X - 1, pStart.Y - 1), new PointF(pStart.X + 1, pStart.Y + 1), new PointF(pEnd.X - 1, pEnd.Y -1), new PointF(pEnd.X + 1, pEnd.Y + 1) });
                        gr.DrawLine(Pens.Red, pStart, pEnd);
                    }
                }

                pictureBoxSkeleton.Image = skeletonImage;
            }
        }

        /// <summary>
        /// Load next directory data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonLoadNext_Click(object sender, EventArgs e)
        {
            string folderPath = textBoxFolderLocation.Text;
            int index = folderPath.LastIndexOf("\\");
            string parentfolderPath = folderPath.Substring(0, index);
            string folderName = folderPath.Substring(index + 1);
            string [] allDirectories = Directory.GetDirectories(parentfolderPath);
            string directoryToLoad = "";
            for (int i = 0; i <allDirectories.Length;i++)
            {
                if (allDirectories[i].Contains(folderName))
                {
                    directoryToLoad = (i == allDirectories.Length - 1 ? allDirectories[0] : allDirectories[i + 1]);
                }
            }
            textBoxFolderLocation.Text = directoryToLoad;
            LoadHandData();
        }

        private void buttonLoadPrevious_Click(object sender, EventArgs e)
        {
            string folderPath = textBoxFolderLocation.Text;
            int index = folderPath.LastIndexOf("\\");
            string parentfolderPath = folderPath.Substring(0, index);
            string folderName = folderPath.Substring(index + 1);
            string[] allDirectories = Directory.GetDirectories(parentfolderPath);
            string directoryToLoad = "";
            for (int i = 0; i < allDirectories.Length; i++)
            {
                if (allDirectories[i].Contains(folderName))
                {
                    directoryToLoad = (i == 0 ? allDirectories[allDirectories.Length - 1] : allDirectories[i - 1]);
                }
            }
            textBoxFolderLocation.Text = directoryToLoad;
            LoadHandData();
        }       
    }
}
